#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  int fd[2];
  if (pipe(fd) == -1) {
    int err = errno;
    perror("pipe");
    return err;
  }
  char buffer[4096];
  strcpy(buffer, "Hello pipe\n");
  size_t len = strlen(buffer);

  ssize_t bytes_written = write(fd[1], buffer, len);
  if (bytes_written == -1) {
    int err = errno;
    perror("write");
    return err;
  }
  assert(bytes_written == len);
  close(fd[1]);

  ssize_t bytes_read;
  while ((bytes_read = read(fd[0], buffer, sizeof(buffer))) > 0) {
    assert(bytes_read == len);
    printf("read: %.*s", (int) len, buffer);
  }
  if (bytes_read == -1) {
    int err = errno;
    perror("read");
    return err;
  }
  assert(bytes_read == 0);
  return 0;
}
